package com.engineering.elink.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
 * Jedis池化
 *
 */
public class MyJedis {
	private static JedisPool pool = null;
	
	private MyJedis() {}
	private static void initialPool(){
		JedisPoolConfig config = new JedisPoolConfig();
//		config.setMaxTotal(20000);
		config.setMaxIdle(-1);
//		config.setMaxWaitMillis(5*1000);
		config.setTestOnBorrow(true);
		pool = new JedisPool(config, RedisConfig.host, RedisConfig.port,RedisConfig.timeout,RedisConfig.password);
	}
	
	
	/**
     * 在多线程环境同步初始化
     */
    private static synchronized void poolInit() {
        if (pool == null) {  
            initialPool();
        }
    }
	
    /**
     * 同步获取Jedis实例
     * @return Jedis
     */
    public synchronized static Jedis getJedisInstance() {  
        if (pool == null) {  
            poolInit();
        }
        Jedis jedis = null;
        try {  
            if (pool != null) {  
                jedis = pool.getResource(); 
            }
        } catch (Exception e) {  
            System.out.println("Get jedis error : "+e);
        }finally{
//        	returnJedis(jedis);
        }
        return jedis;
    }
	/**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnJedis(final Jedis jedis) {
        if (jedis != null && pool !=null) {
            pool.returnResource(jedis);
        }
    }
	
}
